package com.ydd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.constant.MessageConstant;
import com.ydd.context.BaseContext;
import com.ydd.dto.*;
import com.ydd.entity.*;
import com.ydd.entity.YddTag;
import com.ydd.exception.BaseException;
import com.ydd.mapper.*;
import com.ydd.result.PageResult;
import com.ydd.service.SysConfigService;
import com.ydd.service.UserIndexService;
import com.ydd.vo.*;
import com.ydd.vo.common.AllCate;
import com.ydd.vo.common.AllData;
import com.ydd.vo.common.Config;
import com.ydd.vo.common.ConfigList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author fang
 * @Date 2023-05-29 16:34
 */
@Service
public class UserIndexServiceImpl implements UserIndexService {
    @Autowired
    YddCateMapper yddCateMapper;
    @Autowired
    YddArticleMapper yddArticleMapper;
    @Autowired
    YddTagMapper yddTagMapper;
    @Autowired
    YddLinkMapper yddLinkMapper;
    @Autowired
    YddAdvimgMapper yddAdvimgMapper;
    @Autowired
    SysConfigServiceImpl sysConfigService;
    @Autowired
    YddUserDataMapper yddUserDataMapper;
    @Autowired
    YddUserMapper yddUserMapper;

    /**
     * 前台-基础数据-文章列表数据
     *
     * @param articlePageDTO
     * @return
     */
    @Override
    public IndexArticleListVO list(ArticlePageDTO articlePageDTO) {
        Integer pageNum = Integer.valueOf(articlePageDTO.getPage());
        Integer pageSize = Integer.valueOf(articlePageDTO.getLimit());
        PageHelper.startPage(pageNum, pageSize);
        String cateid = articlePageDTO.getCateid().toString();
        Page<ArticleVO> page = yddArticleMapper.getByCateId(cateid);
        PageResult<ArticleVO> pageResult = new PageResult<>();
        long total = page.getTotal();
        pageResult.setCount(total);
        pageResult.setCurrentPage(pageNum);
        int totalPage = (int) total / pageSize;
        pageResult.setTotalPages(total % pageSize == 0 ? totalPage : (totalPage + 1));
        pageResult.setPageSize(pageSize);
        pageResult.setData(page.getResult());
        IndexArticleListVO indexArticleListVO = new IndexArticleListVO(pageResult);
        return indexArticleListVO;
    }

    /**
     * 前台-基础数据-首页和全局数据
     *
     * @return
     */
    @Override
    public IndexIndexVO index() {
        List<CateVO> allCate = new ArrayList<>();
        Config config = new Config();
        List<TagVO> allTag = new ArrayList<>();
        List<LinkVO> allLink = new ArrayList<>();
        List<AdvimgVO> banner = new ArrayList<>();
        List<AdvimgVO> sideBanner = new ArrayList<>();
        List<AdvimgVO> showBanner = new ArrayList<>();

        //allTag
        List<YddTag> yddTags = yddTagMapper.selectList(null);
        for (YddTag yddTag : yddTags) {
            TagVO tagVO = new TagVO();
            BeanUtils.copyProperties(yddTag, tagVO);
            tagVO.setDefault_data(yddTag.getDefaultData());
            allTag.add(tagVO);
        }
        //allLink
        List<YddLink> yddLinks = yddLinkMapper.selectList(null);
        for (YddLink yddLink : yddLinks) {
            LinkVO linkVO = new LinkVO();
            BeanUtils.copyProperties(yddLink, linkVO);
            linkVO.setDefault_data(yddLink.getDefaultData());
            allLink.add(linkVO);
        }
        //allCate
        List<YddCate> yddCates = yddCateMapper.selectList(null);
        for (YddCate yddCate : yddCates) {
            CateVO cateVO = new CateVO();
            BeanUtils.copyProperties(yddCate, cateVO);
            cateVO.setSort_num(yddCate.getSortNum());
            allCate.add(cateVO);
        }
        //banner
        banner = yddAdvimgMapper.getBanner("首页Banner");
        sideBanner = yddAdvimgMapper.getBanner("首页小广告位");
        showBanner = yddAdvimgMapper.getBanner("详情页广告位");

        //config
        //1.list
        List<ConfigList> configLists = sysConfigService.getConfigLists();
        //2.allData
        List<AllData> allDataList = sysConfigService.getAllDataList();
        config.setList(configLists);
        config.setAllData(allDataList);


        IndexIndexVO indexVO = IndexIndexVO.builder()
                .allCate(allCate)
                .config(config)
                .allTag(allTag)
                .allLink(allLink)
                .banner(banner)
                .sideBanner(sideBanner)
                .showBanner(showBanner)
                .build();
        return indexVO;
    }

    /**
     * 前台-基础数据-推荐文章/最新文章
     * 最新文章：按时间排序
     *
     * @param type
     * @return
     */
    @Override
    public IndexArticleVO recommendOrHot(String type) {
        IndexArticleVO indexArticleVO = new IndexArticleVO();
        indexArticleVO.setDesc(type);
        List<ArticleVO> list = null;
        if (type.equals("recommend")) {
            list = yddArticleMapper.recommendOrHot("and ishot = 1 order by lovenum");
        } else {
            list = yddArticleMapper.recommendOrHot("and ishot = 1 and istop = 1 order by lovenum");
        }
        indexArticleVO.setList(list);
        return indexArticleVO;
    }

    /**
     * 前台-基础数据-热门置顶文章数据
     * new接口
     * @param articlePageDTO
     * @return
     */
    @Override
    public IndexNewVO newArticle(ArticlePageDTO articlePageDTO) {
        //num_day：24小时最新文章数量
        long beginDayTime = LocalDateTime.now().minusHours(24).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        Integer numDay = yddArticleMapper.getNumDayByTime(beginDayTime, null);
        //num_week：一周文章最新数量
        long beginWeekTime = LocalDateTime.now().minusDays(7).with(LocalTime.MIN).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        long endWeekTime = LocalDateTime.now().minusDays(1).with(LocalTime.MAX).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        Integer numWeek = yddArticleMapper.getNumDayByTime(beginWeekTime, endWeekTime);

        //list：最新文章
        Integer pageNum = Integer.valueOf(articlePageDTO.getPage());
        Integer pageSize = Integer.valueOf(articlePageDTO.getLimit());
        PageHelper.startPage(pageNum, pageSize);
        Page<ArticleVO> page = yddArticleMapper.getNewArticle();
        PageResult<ArticleVO> pageResult = new PageResult<>();
        long total = page.getTotal();
        pageResult.setCount(total);
        pageResult.setCurrentPage(pageNum);
        int totalPage = (int) total / pageSize;
        pageResult.setTotalPages(total % pageSize == 0 ? totalPage : (totalPage + 1));
        pageResult.setPageSize(pageSize);
        pageResult.setData(page.getResult());

        //封装数据，返回数据
        IndexNewVO indexNewVO = IndexNewVO.builder()
                .desc("首页大列表")
                .num_day(numDay)
                .num_week(numWeek)
                .list(pageResult)
                .build();
        return indexNewVO;
    }

    /**
     * 前台-基础数据-文章详情数据
     *
     * @param id
     * @return
     */
    @Override
    public IndexShowVO show(Long id) {
        //获取相邻文章数据
        List<Long> ids = yddArticleMapper.getAllId();
        int index = ids.indexOf(id);
        //上一篇文章
        YddArticle prevArticle = null;
        if (index >= 1) {
            prevArticle = yddArticleMapper.selectById(ids.get(index - 1));
        }
        List<YddArticle> prev = new ArrayList<>();
        prev.add(prevArticle);
        //下一篇文章
        YddArticle nextArticle = null;
        if (index < ids.size() - 1) {
            nextArticle = yddArticleMapper.selectById(ids.get(index + 1));
        }
        List<YddArticle> next = new ArrayList<>();
        next.add(nextArticle);

        //推荐文章数据
        List<ArticleVO> recommend = yddArticleMapper.getRecommendByCate(id);

        //文章详细信息
        ArticleVO articleVO = yddArticleMapper.selectVOById(id);
        //判断用户是否登陆：展示是否点赞和是否收藏
        Long userId = BaseContext.getCurrentId();
        if (userId != null) {
            Integer likeNum = yddUserDataMapper.isLikeOrCollect(id, userId, "1");
            Integer collectNum = yddUserDataMapper.isLikeOrCollect(id, userId, "2");
            articleVO.setIsLike(likeNum > 0 ? "true" : "false");
            articleVO.setIsCollect(collectNum > 0 ? "true" : "false");
        }

        IndexShowVO indexShowVO = IndexShowVO.builder()
                .prev(prev)
                .next(next)
                .info(articleVO)
                .recommend(recommend)
                .build();

        return indexShowVO;
    }

    /**
     * 用户注册接口
     * @param loginAndRegDTO
     * @return
     */
    @Override
    public YddUser reg(LoginAndRegDTO loginAndRegDTO) {
        String mobile = loginAndRegDTO.getMobile();
        String password = loginAndRegDTO.getPassword();
        String md5 = DigestUtils.md5DigestAsHex(password.getBytes());
        loginAndRegDTO.setPassword(null);
        YddUser yddUser = yddUserMapper.findByCondition(loginAndRegDTO);
        if(yddUser!=null){
            throw new BaseException("手机号已被注册");
        }
        yddUser = YddUser.builder().mobile(mobile).password(md5).username("无名氏").build();
        yddUserMapper.insert(yddUser);
        return yddUser;
    }
}
